/**
 * 
 */
package com.mnurre.shopping.assistant;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * @author michael
 *
 */
public class TaxRateData{
	
	private static final String TAG = "TaxRateData";
	private Context mContext;
	private DataManager mDataManager;
	private SQLiteDatabase mDb;
	
	public TaxRateData(Context context){
		Log.d(TAG, "In TaxRateData ctor. Setting the context to the callee.");
		mContext = context;
	}
	
	public TaxRateData open() throws SQLException {
		Log.d(TAG, "open called on TaxRateData. Creating a new DatabaseHelper and getting a writable database.");
		mDataManager = new DataManager(mContext);
		mDb = mDataManager.getWritableDatabase();
		Log.d(TAG, "Returning this instance.");
		return this;
	}
	
	public void close(){
		Log.d(TAG, "close called on TaxRateData. Closing the DatabaseHelper.");
		mDataManager.close();
	}

	public String getRate(){
		Log.d(TAG, "getRate called. Querying the underlying database to get the latest rate.");
		Cursor cursor = mDb.query(DataManager.Tables.TaxRate.TABLE_NAME, new String[] { DataManager.Tables.TaxRate.COLUMN_RATE }, null, null, null, null, null);
		Log.d(TAG, "Cursor returned. Checking the row count to see if we have anything.");
		if(cursor.getCount() != 0){
			Log.d(TAG, "We have records. Moving to the last and getting the value at column 0 (the only one returned)");
			cursor.moveToLast();
			return cursor.getString(0);
		} else {
			Log.d(TAG, "No records contained in cursor. Returning 0.0 as the default tax rate.");
			return "0.0";
		}
	}
	
	public boolean updateRate(String rate){
		ContentValues values = new ContentValues();
		values.put(DataManager.Tables.TaxRate.COLUMN_RATE, rate);
		return mDb.insert(DataManager.Tables.TaxRate.TABLE_NAME, null, values) != -1;
	}
}